'use client';

import { useState, useEffect } from 'react';
import { motion } from "framer-motion";
import { ShoppingCartIcon, HeartIcon} from "@heroicons/react/24/outline";
import { Button, Rate, Badge, Pagination } from 'antd';

// Mock数据 - 电子产品类别
const mockProducts = [
  {
    id: 1,
    name: "iPhone 15 Pro Max",
    price: 9999,
    originalPrice: 11999,
    discount: 17,
    rating: 4.8,
    reviewCount: 324,
    image: "📱",
    isFavorite: false,
    isNew: true,
    category: "electronics",
    brand: "Apple",
    features: ["6.7英寸", "A17 Pro芯片", "钛金属机身"]
  },
  {
    id: 2,
    name: "Samsung Galaxy S24 Ultra",
    price: 8999,
    originalPrice: 9999,
    discount: 10,
    rating: 4.7,
    reviewCount: 218,
    image: "📱",
    isFavorite: true,
    isNew: true,
    category: "electronics",
    brand: "Samsung",
    features: ["6.8英寸", "骁龙8 Gen 3", "200MP相机"]
  },
  {
    id: 3,
    name: "MacBook Pro 16英寸 M3",
    price: 19999,
    originalPrice: 21999,
    discount: 9,
    rating: 4.9,
    reviewCount: 156,
    image: "💻",
    isFavorite: false,
    isNew: true,
    category: "electronics",
    brand: "Apple",
    features: ["M3 Pro芯片", "18GB内存", "512GB SSD"]
  },
  {
    id: 4,
    name: "Dell XPS 13 Plus",
    price: 12999,
    originalPrice: 14999,
    discount: 13,
    rating: 4.5,
    reviewCount: 89,
    image: "💻",
    isFavorite: false,
    isNew: false,
    category: "electronics",
    brand: "Dell",
    features: ["13.4英寸", "Intel i7", "16GB内存"]
  },
  {
    id: 5,
    name: "Sony WH-1000XM5 降噪耳机",
    price: 2499,
    originalPrice: 2999,
    discount: 17,
    rating: 4.8,
    reviewCount: 421,
    image: "🎧",
    isFavorite: true,
    isNew: false,
    category: "electronics",
    brand: "Sony",
    features: ["主动降噪", "30小时续航", "触控操作"]
  },
  {
    id: 6,
    name: "iPad Pro 12.9英寸 M2",
    price: 8999,
    originalPrice: 9999,
    discount: 10,
    rating: 4.7,
    reviewCount: 178,
    image: "📱",
    isFavorite: false,
    isNew: true,
    category: "electronics",
    brand: "Apple",
    features: ["M2芯片", "Liquid Retina XDR", "支持Apple Pencil"]
  },
  {
    id: 7,
    name: "Nintendo Switch OLED",
    price: 2299,
    originalPrice: 2599,
    discount: 12,
    rating: 4.9,
    reviewCount: 532,
    image: "🎮",
    isFavorite: false,
    isNew: false,
    category: "electronics",
    brand: "Nintendo",
    features: ["7英寸OLED屏幕", "可拆卸手柄", "64GB存储"]
  },
  {
    id: 8,
    name: "Canon EOS R5 全画幅微单",
    price: 19999,
    originalPrice: 22999,
    discount: 13,
    rating: 4.8,
    reviewCount: 97,
    image: "📷",
    isFavorite: false,
    isNew: true,
    category: "electronics",
    brand: "Canon",
    features: ["45MP传感器", "8K视频录制", "双核CMOS AF"]
  }
];

const brands = [
  { id: 'apple', name: 'Apple' },
  { id: 'samsung', name: 'Samsung' },
  { id: 'sony', name: 'Sony' },
  { id: 'dell', name: 'Dell' },
  { id: 'canon', name: 'Canon' },
  { id: 'nintendo', name: 'Nintendo' }
];

const priceRanges = [
  { id: 'all', name: '所有价格' },
  { id: '0-3000', name: '¥0 - ¥3000' },
  { id: '3000-6000', name: '¥3000 - ¥6000' },
  { id: '6000-10000', name: '¥6000 - ¥10000' },
  { id: '10000+', name: '¥10000以上' }
];

// 产品卡片组件
function ProductCard({ product }) {
  const [isFavorite, setIsFavorite] = useState(product.isFavorite);
  
  return (
    <motion.div
      className="border border-gray-200 rounded-lg hover:shadow-lg transition-shadow relative bg-white"
      whileHover={{ y: -5 }}
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {product.isNew && (
        <Badge.Ribbon text="新品" color="red">
          <div className="absolute top-2 left-2 bg-red-500 text-white text-xs px-2 py-1 rounded z-10">
            新品
          </div>
        </Badge.Ribbon>
      )}
      <button 
        className="absolute top-2 right-2 p-1 rounded-full hover:bg-gray-100 z-10"
        onClick={() => setIsFavorite(!isFavorite)}
      >
        <HeartIcon className={`h-5 w-5 ${isFavorite ? 'text-red-500 fill-current' : 'text-gray-400'}`} />
      </button>
      
      <div className="aspect-square bg-gray-100 rounded-lg mb-4 flex items-center justify-center">
        <span className="text-6xl">{product.image}</span>
      </div>
      
      <div className="p-4">
        <h3 className="font-medium text-gray-900 truncate">{product.name}</h3>
        
        <div className="flex items-center mt-1">
          <Rate disabled defaultValue={Math.floor(product.rating)} allowHalf />
          <span className="text-xs text-gray-500 ml-1">({product.reviewCount})</span>
        </div>
        
        <ul className="mt-2 text-xs text-gray-500 h-10 overflow-hidden">
          {product.features.map((feature, index) => (
            <li key={index} className="truncate">• {feature}</li>
          ))}
        </ul>
        
        <div className="flex items-center mt-2">
          <span className="text-lg font-bold text-gray-900">¥{product.price.toLocaleString()}</span>
          {product.originalPrice > product.price && (
            <>
              <span className="text-sm text-gray-500 line-through ml-2">¥{product.originalPrice.toLocaleString()}</span>
              <span className="text-sm font-medium text-red-500 ml-2">-{product.discount}%</span>
            </>
          )}
        </div>
        
        <div className="mt-4 flex space-x-2">
          <Button 
            type="primary" 
            className="flex-1 flex items-center justify-center"
            icon={<ShoppingCartIcon className="h-4 w-4 mr-1" />}
          >
            加入购物车
          </Button>
        </div>
      </div>
    </motion.div>
  );
}

// 过滤面板组件
function FilterPanel({ onFilterChange }) {
  const [selectedBrands, setSelectedBrands] = useState([]);
  const [selectedPriceRange, setSelectedPriceRange] = useState('all');
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);

  const handleBrandChange = (brandId) => {
    const newSelectedBrands = selectedBrands.includes(brandId)
      ? selectedBrands.filter(id => id !== brandId)
      : [...selectedBrands, brandId];
    
    setSelectedBrands(newSelectedBrands);
    onFilterChange({ brands: newSelectedBrands, priceRange: selectedPriceRange });
  };

  const handlePriceRangeChange = (rangeId) => {
    setSelectedPriceRange(rangeId);
    onFilterChange({ brands: selectedBrands, priceRange: rangeId });
  };

  return (
    <>
      {/* 移动端过滤按钮 */}
      <div className="md:hidden mb-4">
        <Button 
          type="default" 
          className="w-full flex items-center justify-center"
          onClick={() => setMobileFiltersOpen(true)}
        >
          筛选条件
        </Button>
      </div>

      {/* 移动端过滤抽屉 */}
      {mobileFiltersOpen && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="fixed inset-0 bg-black bg-opacity-25" onClick={() => setMobileFiltersOpen(false)}></div>
          <div className="relative bg-white w-80 h-full p-4 overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium">筛选条件</h3>
              <button 
                className="text-gray-500"
                onClick={() => setMobileFiltersOpen(false)}
              >
                ✕
              </button>
            </div>
            
            <div className="mb-6">
              <h4 className="font-medium mb-2">品牌</h4>
              <div className="space-y-2">
                {brands.map(brand => (
                  <label key={brand.id} className="flex items-center">
                    <input
                      type="checkbox"
                      checked={selectedBrands.includes(brand.id)}
                      onChange={() => handleBrandChange(brand.id)}
                      className="rounded text-blue-600"
                    />
                    <span className="ml-2 text-gray-700">{brand.name}</span>
                  </label>
                ))}
              </div>
            </div>
            
            <div>
              <h4 className="font-medium mb-2">价格区间</h4>
              <div className="space-y-2">
                {priceRanges.map(range => (
                  <label key={range.id} className="flex items-center">
                    <input
                      type="radio"
                      name="priceRange"
                      checked={selectedPriceRange === range.id}
                      onChange={() => handlePriceRangeChange(range.id)}
                      className="rounded text-blue-600"
                    />
                    <span className="ml-2 text-gray-700">{range.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 桌面端过滤面板 */}
      <div className="hidden md:block w-full md:w-64 flex-shrink-0">
        <div className="bg-white p-4 rounded-lg border border-gray-200 sticky top-4">
          <h3 className="font-medium text-lg mb-4">筛选条件</h3>
          
          <div className="mb-6">
            <h4 className="font-medium mb-2">品牌</h4>
            <div className="space-y-2">
              {brands.map(brand => (
                <label key={brand.id} className="flex items-center">
                  <input
                    type="checkbox"
                    checked={selectedBrands.includes(brand.id)}
                    onChange={() => handleBrandChange(brand.id)}
                    className="rounded text-blue-600"
                  />
                  <span className="ml-2 text-gray-700">{brand.name}</span>
                </label>
              ))}
            </div>
          </div>
          
          <div>
            <h4 className="font-medium mb-2">价格区间</h4>
            <div className="space-y-2">
              {priceRanges.map(range => (
                <label key={range.id} className="flex items-center">
                  <input
                    type="radio"
                    name="priceRange"
                    checked={selectedPriceRange === range.id}
                    onChange={() => handlePriceRangeChange(range.id)}
                    className="rounded text-blue-600"
                  />
                  <span className="ml-2 text-gray-700">{range.name}</span>
                </label>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// 主页面组件
export default function Electronics() {
  const [filteredProducts, setFilteredProducts] = useState(mockProducts);
  const [currentPage, setCurrentPage] = useState(1);
  const productsPerPage = 8;

  // 应用过滤器
  const applyFilters = ({ brands, priceRange }) => {
    let result = [...mockProducts];
    
    // 品牌过滤
    if (brands.length > 0) {
      result = result.filter(product => 
        brands.includes(product.brand.toLowerCase())
      );
    }
    
    // 价格范围过滤
    if (priceRange !== 'all') {
      switch(priceRange) {
        case '0-3000':
          result = result.filter(product => product.price <= 3000);
          break;
        case '3000-6000':
          result = result.filter(product => product.price > 3000 && product.price <= 6000);
          break;
        case '6000-10000':
          result = result.filter(product => product.price > 6000 && product.price <= 10000);
          break;
        case '10000+':
          result = result.filter(product => product.price > 10000);
          break;
      }
    }
    
    setFilteredProducts(result);
    setCurrentPage(1); // 重置到第一页
  };

  // 计算当前页产品
  const indexOfLastProduct = currentPage * productsPerPage;
  const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
  const currentProducts = filteredProducts.slice(indexOfFirstProduct, indexOfLastProduct);
  const totalPages = Math.ceil(filteredProducts.length / productsPerPage);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <section className="bg-gradient-to-r from-blue-600 to-indigo-700 text-white py-12">
        <div className="container mx-auto px-4">
          <div className="flex flex-col items-center justify-center">
            <div className="flex items-center justify-center mb-4">
              <span className="text-5xl mr-4">📱</span>
              <h1 className="text-3xl md:text-4xl font-bold">电子产品</h1>
            </div>
            <p className="text-center text-blue-100 max-w-2xl">
              探索最新、最热门的电子设备，包括智能手机、笔记本电脑、平板电脑和更多智能设备
            </p>
          </div>
        </div>
      </section>

      {/* 主要内容区 */}
      <section className="py-8">
        <div className="container mx-auto px-4">
          <div className="flex flex-col md:flex-row gap-6">
            {/* 过滤面板 */}
            <FilterPanel onFilterChange={applyFilters} />
            
            {/* 产品列表区 */}
            <div className="flex-grow">
              {/* 头部工具栏 */}
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                <div>
                  <h2 className="text-xl font-bold text-gray-900">
                    精选电子产品 <span className="text-gray-500 text-base">({filteredProducts.length} 件商品)</span>
                  </h2>
                </div>
                
                <div className="flex items-center space-x-2 w-full sm:w-auto">
                  <select className="border border-gray-300 rounded px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option>默认排序</option>
                    <option>价格从低到高</option>
                    <option>价格从高到低</option>
                    <option>最新上架</option>
                    <option>销量最高</option>
                    <option>评价最高</option>
                  </select>
                </div>
              </div>
              
              {/* 产品网格 */}
              {currentProducts.length === 0 ? (
                <div className="bg-white rounded-lg border border-gray-200 p-12 text-center">
                  <h3 className="text-lg font-medium text-gray-900 mb-2">未找到相关产品</h3>
                  <p className="text-gray-500 mb-4">尝试调整筛选条件以查看结果</p>
                  <Button 
                    type="primary" 
                    onClick={() => window.location.reload()}
                  >
                    清除所有筛选
                  </Button>
                </div>
              ) : (
                <>
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    {currentProducts.map((product, index) => (
                      <motion.div
                        key={product.id}
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: index * 0.1 }}
                      >
                        <ProductCard product={product} />
                      </motion.div>
                    ))}
                  </div>
                  
                  {/* 分页控件 */}
                  {totalPages > 1 && (
                    <div className="mt-8 flex justify-center">
                      <Pagination
                        current={currentPage}
                        total={filteredProducts.length}
                        pageSize={productsPerPage}
                        onChange={(page) => setCurrentPage(page)}
                        showSizeChanger={false}
                      />
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}